package com.yu.core.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.stonehenge.backend.tools.geo.GeoU;
import com.yu.interceptor.UserInterceptor;
import com.yu.model.Code;
import com.yu.model.Config;
import com.yu.model.Focus;
import com.yu.model.House;
import com.yu.model.Order;
import com.yu.model.User;
import com.yu.util.CommonUtil;
import com.yu.util.CookiesUtil;
import com.yu.util.DateUtil;
import com.yu.util.GetWxOrderno;
import com.yu.util.QQSMSComponent;
import com.yu.util.Sha1Util;
import com.yu.util.StringUtil;
import com.yu.util.TenpayUtil;
import com.yu.util.Toolkit;
import com.yu.util.WeiXinUtil;

import net.sf.json.JSONArray;

public class IndexController extends Controller {
	
	
	public void bind(){
		try {
			String code = getPara("code");
		      if(!StringUtil.isEmpty(code)){
		          String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WeiXinUtil.appid+"&secret="+WeiXinUtil.appsecret+"&code="+code+"&grant_type=authorization_code";
		          net.sf.json.JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
//		          System.out.println(jsonObject);
		          if (null != jsonObject) {
		              String openId = jsonObject.getString("openid");
		              String access_token = jsonObject.getString("access_token");
		              String URL2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" +access_token+ "&openid="+openId+ "&lang=zh_CN";
		              net.sf.json.JSONObject myJsonObject1 = CommonUtil.httpsRequest(URL2, "GET", null);
//		              System.out.println(myJsonObject1);
		              User user = (User) getSession().getAttribute("user");
		              user.set("wxid", openId);
	                  String headimgurl = myJsonObject1.getString("headimgurl");
	                  user.set("head", headimgurl);
	                  user.update();
		          }
		          main();
		      } else {
	              String redirect_uri ="http://fangdong580.com/index/bind";
	              String scope = "snsapi_userinfo";
	              String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeiXinUtil.appid +"&redirect_uri="+redirect_uri +"&response_type=code&scope="+scope+"&state=wx#wechat_redirect";
//	              System.out.println("url:"+url);
	              redirect(url);
		     }
		 }catch (Exception e){
       	  System.out.println(e.getMessage());
             e.printStackTrace();
         }
	  }
	
	public void index() {
		User user = getSessionAttr("user");
		if (user != null){
			// 跳转 主页
			main();
		} else {
			render("login.html");
		}
    }
	
	public void sendcode(){
		String phone = getPara("phone");
		System.out.println(phone);
		if(phone.length() != 11){
			renderText("手机格式错误!");
			return;
		}
		List<Code> codeList = Code.dao.find("select * from w_code where mobile ='" +phone +"'");
		for(Code code:codeList){
			code.delete();
		}
		int random = (int)(Math.random()*(9999-1000+1))+1000;
		Code code = new Code();
		code.set("mobile", phone);
		code.set("code", random);
		code.set("createtime", System.currentTimeMillis());
		code.save();
		try {
			// TODO 发送短信
			QQSMSComponent.sendSMSInvitation(phone, String.valueOf(random));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		renderText("发送成功！" + random);
	}
	
	
	@Before(UserInterceptor.class)
	public void main(){
		User user = getSessionAttr("user");
		int type = user.getInt("type");
		if(StringUtil.isEmpty(String.valueOf(user.get("wxid")))){
			bind();
		} else {
			if (type ==2){
				// 房东
				render("owner.html");
			} else {
				// 管家
				setAttr("money", user.get("money"));
				render("service.html");
			}
			// 半年
			int time = 60*60*24*30*6;
			CookiesUtil.add(getResponse(), "wxid", String.valueOf(user.get("wxid")), time);
		}
		
	}
	
	public void owner() {
		render("owner.html");
	}
	
	@Before(UserInterceptor.class)
	public void myHouseList() {
		User user = getSessionAttr("user");
		int userid = user.getInt("id");
		List<House> houseList = House.dao.find("select h.*, case  when h.status  = 0 then '未审核' else '审核通过' end as statusname  from w_house as h where  h.userid = " + userid);
		setAttr("houseList", houseList);
		render("houseList.html");
    }
	
	@Before(UserInterceptor.class)
	public void house() {
		User user = getSessionAttr("user");
		if (user == null){
			render("login.html");
		} else{
			setAttr("user", user);
			int type = user.getInt("type");
			if (type ==2){
				setAttr("equipList", Config.dao.find("select * from w_config where type =101 "));
				House house = House.dao.findById(getPara("id"));
				int exitGoodCnt = 0;
				int goodCnt = 9;
				setAttr("id", 0);
				setAttr("btn", "确定添加");
				
				
				if(house != null){
					setAttr("id",  house.get("id"));
					setAttr("name", house.get("name"));
					setAttr("province", house.get("province"));
					setAttr("city", house.get("city"));
					setAttr("village", house.get("village"));
					setAttr("road", house.get("road"));
					setAttr("address", house.get("address"));
					setAttr("equip", house.get("equip"));
					setAttr("area", house.get("area"));
					setAttr("resid", house.get("resid"));
					// 布草 
					setAttr("linen", house.get("linen"));
					// 1.5米 床单
					setAttr("five", house.get("five"));
					// 1.8米 床单
					setAttr("eight", house.get("eight"));
					setAttr("note", house.get("note"));
					// 屋内照片
					String goods =  house.getStr("goods");
					setAttr("goods", goods);
					if (!StringUtil.isEmpty(goods)){
						String[] goodsArray = goods.split(",");
						exitGoodCnt = goodsArray.length;
						goodCnt = goodCnt - exitGoodCnt;
						setAttr("goodsArray", goodsArray);
					}
					
					setAttr("btn", "确定修改");
				}
				
				setAttr("exitGoodCnt", exitGoodCnt);
				setAttr("goodCnt", goodCnt); 
				render("house.html");
			}
		}
    }
	
	@Before(UserInterceptor.class)
	public void houseSave(){
		User user = getSessionAttr("user");
		House house = House.dao.findById(getPara("id"));
		boolean editflg = true;
		if (house == null){
			editflg = false;
			house = new House();
			house.set("userid", getPara("ownerid"));
			//			ownername
//			
			house.set("createtime", System.currentTimeMillis());
			house.set("status", 0);
			house.set("valid", 0);
		} 
		if(user != null){
			house.set("userid", user.getInt("id"));
			house.set("ownername", user.get("name"));
			house.set("ownermobile", user.get("mobile"));
		}
		house.set("name", getPara("name"));
		if (!StringUtil.isEmpty(getPara("province")))
			house.set("province", getPara("province"));
		if (!StringUtil.isEmpty(getPara("city")))
			house.set("city", getPara("city"));
		if (!StringUtil.isEmpty(getPara("village")))
			house.set("village", getPara("village"));
		if (!StringUtil.isEmpty(getPara("road")))
			house.set("road", getPara("road"));
		house.set("address", getPara("address"));
		house.set("area", getPara("area"));
		house.set("equip", getPara("equip"));
		house.set("resid", getPara("resid"));
		house.set("linen", getPara("linen"));
		house.set("five", getPara("five"));
		house.set("eight", getPara("eight"));
		house.set("goods", getPara("goods"));
		house.set("note", getPara("note"));
		
		try{
			if (editflg)
				house.update();
			else
				house.save();
		}catch (Exception e) {
			e.printStackTrace();
		}
		renderText("操作成功！");
	}
	
	public void register() {
		System.out.println("--------register-----------");
		render("register.html");
    }
	
	public void forgot() {
		render("forgot.html");
    }
	public void usersave2() {
		String phone = getPara("phone");
		Code code = Code.dao.findFirst("select * from w_code where code =" +getPara("code") +" and mobile = "+phone);
		if (code == null){
			renderText("验证码错误");
			return;
		}
		code.delete();
		User existUser = User.dao.findFirst("select * from w_user where account = '"+phone+"'");
		if (existUser == null){
			renderText("账号不存在");
			return;
		}
		existUser.set("password", getPara("password"));
		existUser.update();
		
		setSessionAttr("user", existUser);
		renderText("操作成功！跳转到主页");
	}
	/**
	 * 用户注册并登录
	 */
	public void usersave() {
		String phone = getPara("phone");
		Code code = Code.dao.findFirst("select * from w_code where code =" +getPara("code") +" and mobile = "+phone);
		if (code == null){
			renderText("验证码错误");
			return;
		}
		User existUser = User.dao.findFirst("select * from w_user where account = '"+phone+"'");
		if (existUser != null){
			setAttr("msg", "账号已存在！");
			renderText("账号已存在");
			return;
		}
		User user = new User();
		user.set("type", 2);
		user.set("createtime", System.currentTimeMillis());
		user.set("valid", 0);
		user.set("account", phone);
		user.set("name", getPara("name"));
		user.set("password", getPara("password"));
		user.set("head", getPara("head"));
		user.set("age", getPara("age"));
		user.set("mobile", phone);
		user.set("scope", getPara("scope"));
		user.save();
		code.delete();
		setSessionAttr("user", user);
		renderText("操作成功！跳转到主页");
    }
	
	public void login() {
		String phone = getPara("phone").trim();
		String password = getPara("password").trim();
		User existUser = User.dao.findFirst("select * from w_user where (type= 2 or type =1 ) and (account = '"+phone+"' or mobile ='"+phone+"') and password='"+password+"'");
		if (existUser == null){
			//CookiesUtil.clear(getRequest(), getResponse());
			renderText("账号或密码错误！");
		} else {
//			setSessionAttr("user", existUser);
			getSession().setAttribute("user", existUser);
			renderText("操作成功！跳转到主页");
		}
    }
	
	/**
	 * 下单页面
	 */
	@Before(UserInterceptor.class)
	public void order() {
		// cookie 中获取 
		User user = getSessionAttr("user");
//		User user = User.dao.findById(2);
		setAttr("username", user.get("name"));
		setAttr("usermobile", user.get("mobile"));
		
		setAttr("rentername", "");
		setAttr("rentermobile", "");
		
		List<House> houseList = House.dao.find("select * from w_house where status =1 and userid = " + user.get("id"));
		for(House h:houseList){
			if (h.getInt("aprice").intValue() > 0 ){
				h.set("aprice", new BigDecimal(h.getInt("aprice")).multiply(getBasePrice(user.getStr("rank"))).setScale(0, BigDecimal.ROUND_UP).intValue());
				System.out.println(new BigDecimal(h.getInt("aprice")).multiply(getBasePrice(user.getStr("rank"))).setScale(0, BigDecimal.ROUND_UP));
			}
		}
		setAttr("hsize", houseList == null ? 0 : houseList.size());
		setAttr("houseList", houseList);
		setAttr("now", DateUtil.getStringDateForH5());
		List<Config> configList = Config.dao.find("select * from w_config where type =10 order by `subtype` asc ,`value` asc ,`key` asc ");
		setAttr("configList", configList);
		setAttr("baseprice", getBasePrice(user.getStr("rank")));
		render("order.html");
	}
	
	private BigDecimal getBasePrice(String level){
		BigDecimal base = new BigDecimal(1);
		if ("lv1".equalsIgnoreCase(level)){
			base = base.multiply(new BigDecimal(0.95));
		} else if ("lv2".equalsIgnoreCase(level)){
			base = base.multiply(new BigDecimal(0.9));
		} else if ("lv3".equalsIgnoreCase(level)){
			base = base.multiply(new BigDecimal(0.85));
		}
		return base;
	}
	
	private static final Map<String,Object> bucao = new HashMap<String,Object>(){
		{
			put("布草清洗", 15);
			put("布草在家清洗", 5);
		}
		
	}; 
	
	
	@Before(UserInterceptor.class)
	public void createOrder(){
		User user = getSessionAttr("user");
		Order order = new Order();
		order.set("uid", user.get("id"));
		order.set("orderid", Toolkit.one.newTradeNo());
		order.set("parentid", 0);
		order.set("status", -1);
		order.set("price", getPara("price"));
		System.out.println(getPara("house"));
		House house = House.dao.findById(getPara("house"));
		// 房源id
		order.set("hid", getPara("house"));
		// 房源名称
		order.set("hname", house.getStr("name"));
		
		// 租客信息
		order.set("rentername", getPara("rentername"));
		order.set("rentermobile", getPara("rentermobile"));
		// 入驻时间
		// 2017-09-14T12:12
		String checkintime = getPara("checkintime").replace("T", " ");
		String checkouttime = getPara("checkouttime").replace("T", " ");
		String endtime = getPara("endtime").replace("T", " ");
		try {
			order.set("checkintime", new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(checkintime).getTime());
			order.set("checkouttime", new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(checkouttime).getTime());
			order.set("endtime", new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(endtime).getTime());
		} catch (ParseException e) {
			System.out.println("checkintime:"+getPara("checkintime"));
			System.out.println("checkouttime:"+getPara("checkouttime"));
			order.set("checkintime", System.currentTimeMillis());
			order.set("checkouttime", System.currentTimeMillis());
		}
		House h = House.dao.findById(getPara("house"));
		if (h ==null){
			return;
		}
		BigDecimal base = new BigDecimal(h.getInt("aprice")).multiply(getBasePrice(user.getStr("rank"))).setScale(0, BigDecimal.ROUND_UP);
		org.json.JSONArray pdetail = new org.json.JSONArray();
		Map<String, Object> detail1 = Maps.newHashMap();
		detail1.put("name", "日常清扫");
		detail1.put("price", base);
		pdetail.put(detail1);

		if (!StringUtil.isEmpty(getPara("linen"))){
			Map<String, Object> detail2 = Maps.newHashMap();
			detail2.put("name", getPara("linen"));
			BigDecimal price = new BigDecimal(getPara("price"));
			detail2.put("price", price.subtract(base));
			detail2.put("1.5米", getPara("five"));
			detail2.put("1.8米", getPara("eight"));
			
			
			pdetail.put(detail2);
		}
		order.set("linen", getPara("linen"));
		order.set("five", getPara("five"));
		order.set("eight", getPara("eight"));
		order.set("note", getPara("note"));
		/*
		if (!StringUtil.isEmpty(getPara("depth"))){
			Map<String, Object> detail2 = Maps.newHashMap();
			detail2.put("name", "厨房深度保洁");
			detail2.put("price", 50);
			pdetail.put(detail2);
		}
		
		if (!StringUtil.isEmpty(getPara("glass"))){
			Map<String, Object> detail3 = Maps.newHashMap();
			detail3.put("name", "全屋玻璃清洁");
			
			detail3.put("price", house.get("aprice"));
			pdetail.put(detail3);
		}
		*/
		order.set("pdetail", pdetail.toString());
		// 预约时间
		order.set("createtime", System.currentTimeMillis());
		order.set("valid", 0);
		order.save();
		setAttr("orderid", order.get("id"));
		setAttr("money", user.get("money"));
		render("choose.html");
	}
	
	@Before(UserInterceptor.class)
	public void choose(){
		User user = getSessionAttr("user");
		setAttr("orderid", getPara("id"));
		Order order = Order.dao.findById(getPara("id"));
		if(order == null || order.getInt("status") == -1){
			orderList();
		} else {
			setAttr("money", user.get("money"));
			render("choose.html");
		}
		
	}
	
	@Before(UserInterceptor.class)
	public void pay(){
		User user = getSessionAttr("user");
		Order order = Order.dao.findById(getPara("orderid"));
		if(order == null ){
			renderText("订单不存在!");
			return;
		} else if (order.getInt("status") != -1){
			renderText("已付款!");
			return;
		} else {
			if ("weixin".equals(getPara("mode"))){
				String appid = "wx191fc28ce039710b";
	            String partner = "1488139512";
	            /*
	            String currTime = TenpayUtil.getCurrTime();
	            //8位日期
	            String strTime = currTime.substring(8, currTime.length());
	            //四位随机数
	            String strRandom = TenpayUtil.buildRandom(4) + "";
	            //10位序列号,可以自行调整。
	            String strReq = strTime + strRandom;
	            //商户号
	            String mch_id = partner;
	            String nonce_str = strReq;
	            //商品描述根据情况修改
	            String body = "jfenz";
	            //商户订单号
	            String out_trade_no = order.getStr("orderid");
	            //订单生成的机器 IP
	            String spbill_create_ip = getRequest().getRemoteAddr();
	            //这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
	            String notify_url ="http://fangdong580.com/index/wxcallback";
	            String trade_type = "JSAPI";
	            SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
	            parameters.put("appid", appid);
	            parameters.put("attach", out_trade_no);
	            parameters.put("body", body);
	            parameters.put("mch_id", partner);
	            parameters.put("nonce_str", nonce_str);
	            parameters.put("notify_url", notify_url);
	            parameters.put("out_trade_no", out_trade_no);

	            parameters.put("spbill_create_ip",spbill_create_ip);
	            parameters.put("total_fee", order.getBigDecimal("price").multiply(new BigDecimal(100)).toString());
	            parameters.put("trade_type", "NATIVE");

	            String sign = WeiXinUtil.createSign("UTF-8", parameters);
	            parameters.put("sign", sign);
	            String requestXML = WeiXinUtil.getRequestXml(parameters);
	            String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	            String codeUrl = new GetWxOrderno().getCodeUrl(createOrderURL,requestXML);
	            setAttr("codeUrl", codeUrl);
	            */
	            String openId = user.getStr("wxid");
	            String currTime = TenpayUtil.getCurrTime();
	            //8位日期
	            String strTime = currTime.substring(8, currTime.length());
	            //四位随机数
	            String strRandom = TenpayUtil.buildRandom(4) + "";
	            //10位序列号,可以自行调整。
	            String strReq = strTime + strRandom;
	            //商户号
	            String mch_id = partner;
	            String nonce_str = strReq;
	            //商品描述根据情况修改
	            String body = "jfenz";
	            //商户订单号
	            String out_trade_no = order.getStr("orderid");
	            //订单生成的机器 IP
	            String spbill_create_ip = getRequest().getRemoteAddr();
	            //这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
	            String notify_url ="http://fangdong580.com/index/wxcallback";
	            String trade_type = "JSAPI";
	            SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
	            parameters.put("appid", appid);
	            parameters.put("attach", out_trade_no);
	            parameters.put("body", body);
	            parameters.put("mch_id", partner);
	            parameters.put("nonce_str", nonce_str);
	            parameters.put("notify_url", notify_url);
	            parameters.put("openid", openId);
	            parameters.put("out_trade_no", out_trade_no);

	            parameters.put("spbill_create_ip",spbill_create_ip);
	            int total_fee = order.getBigDecimal("price").multiply(new BigDecimal(100)).intValue();
	            parameters.put("total_fee", String.valueOf(total_fee));
	            parameters.put("trade_type", "JSAPI");

	            String sign = WeiXinUtil.createSign("UTF-8", parameters);
	            parameters.put("sign", sign);
	            String requestXML = WeiXinUtil.getRequestXml(parameters);
	            String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	            String prepay_id = new GetWxOrderno().getPayNo(createOrderURL,requestXML);  //CommonUtil.httpsRequest(createOrderURL, "POST", requestXML);
	            SortedMap<String, String> finalpackage = new TreeMap<String, String>();
	            String timestamp = Sha1Util.getTimeStamp();
	            String nonceStr2 = nonce_str;
	            String packages = "prepay_id="+prepay_id;
	            finalpackage.put("appId", appid);
	            finalpackage.put("timeStamp", timestamp);
	            finalpackage.put("nonceStr", nonce_str);
	            finalpackage.put("package", packages);
	            finalpackage.put("signType", "MD5");
	            String finalsign = WeiXinUtil.createSign("UTF-8",finalpackage);
//	            return [timestamp:timestamp,nonceStr:nonce_str,p:packages,sign:finalsign]
	            setAttr("timestamp", timestamp);
	            setAttr("nonceStr", nonce_str);
	            setAttr("p", packages);
	            setAttr("sign", finalsign);
//	            System.out.println("packages:"+packages);
//	            System.out.println("sign:"+finalsign);
	            render("wx.html");
			} else {
				BigDecimal balance = user.getBigDecimal("money");
				BigDecimal total = order.getBigDecimal("price");
				if (balance.compareTo(total) == -1){
					renderText("余额不足");
					return ;
				} else {
					user.set("money", balance.subtract(total));
					user.update();
					order.set("status", 0);
					order.update();
					if (!StringUtil.isEmpty(order.getStr("rentermobile"))){
						renterSMS(order.getStr("rentermobile"), order.getLong("checkintime"), order.getLong("checkouttime"));
					}
					House house = House.dao.findById(order.get("fid"));
					if (house != null && house.getDouble("lon").doubleValue() > 0 && house.getDouble("lat").doubleValue() > 0){
						newOrderWeixinNotice(house.getDouble("lon").doubleValue(),house.getDouble("lon").doubleValue(),order,house.getStr("address"));
					}
					String wxid = user.getStr("wxid");
					if (!StringUtil.isEmpty(wxid)){
						WeiXinUtil.moneyChangeNotice(wxid, total, user.getBigDecimal("money"));
					}
					renderText("付款成功!");
					return;
					
				}
			}

		}
	}
	
	public void wxcallback(){
		try {
	    	   BufferedReader br = new BufferedReader(new InputStreamReader(getRequest().getInputStream()));
		       String line = null;
		       StringBuilder sb = new StringBuilder();
		       while((line = br.readLine())!=null){
		           sb.append(line);
		       }
			   String sbStr = sb.toString();
			   System.out.println("wx callback: " +sbStr);
	           Map params = GetWxOrderno.doXMLParse(sbStr);
	           String return_code  = (String) params.get("return_code");
	           if("SUCCESS".equalsIgnoreCase(return_code)){
	        	   Order order = Order.dao.findFirst("select * from w_order where orderid ='"+params.get("trade_no")+"'");
	        	   if (order != null && order.getInt("status") == -1){
	        		   order.set("status", 0);
	        		   order.update();
	        		   if (!StringUtil.isEmpty(order.getStr("rentermobile"))){
							renterSMS(order.getStr("rentermobile"), order.getLong("checkintime"), order.getLong("checkouttime"));
					   }
	        	   }
	        	   
	           }
			   renderText("SUCCESS");
	       } catch (Exception e){
	    	   e.printStackTrace();
	       }
		renderText("FAIL");
	}
	
	/**
	 * 基础清扫服务
	 */
	public void basic(){
		List<Config> configList = Config.dao.find("select * from w_config where type =100 order by subtype asc ");
		setAttr("configList", configList);
		render("basic.html");
	}
	
	/**
	 * 基础清扫服务
	 */
	public void clean(){
		List<Config> configList = Config.dao.find("select * from w_config where type =10 order by `subtype` asc ,`value` asc ,`key` asc ");
		setAttr("configList", configList);
		render("clean.html");
	}
	
	/*
	 * 暂时不用
	private int calculate(int num){
		int result = 0;
		// 是否大于最大值
		Config maxConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =2 order by `key` desc limit 1");
		if (maxConfig != null){
			int maxkey = Integer.parseInt(String.valueOf(maxConfig.get("key")));
			if(num >= maxkey){
				Config lessMaxConfig =  Config.dao.findFirst("select * from w_config where type=10 and subtype =1 order by `value` desc limit 1");
				int value = maxConfig.getInt("value");
				result = lessMaxConfig.getInt("value") + (num- maxkey) * value ;
			} else {
				Config minConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 order by `key` asc limit 1");
				int minkey = Integer.parseInt(String.valueOf(minConfig.get("key")));
				if(num <= minkey){
					result = minConfig.getInt("value");
				} else {
					Config nearConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 and `key` >= "+num+" order by `key` asc limit 1");
					result = nearConfig.getInt("value");
				}
			}
		} else {
			//没有设置最大值，按小于等于最大值计算
			Config minConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 order by `key` asc limit 1");
			int minkey = Integer.parseInt(String.valueOf(minConfig.get("key")));
			if(num <= minkey){
				result = minConfig.getInt("value");
			} else {
				Config nearConfig = Config.dao.findFirst("select * from w_config where type=10 and subtype =1 and `key` >= 30 order by `key` asc limit 1");
				result = nearConfig.getInt("value");
			}
		}
		return result;
	}
	*/
	
	@Before(UserInterceptor.class)
	public void orderList(){
		User user = getSessionAttr("user");
		int uid = user.getInt("id");
		int type = user.getInt("type");
		String sql = "";
		if (type ==2){
			sql ="SELECT o.id,o.hid,o.hname,o.STATUS,FROM_UNIXTIME(o.createtime / 1000,'%Y-%m-%d %h:%i' ) as createtime1 , "+AdminController.case_statusname+"  FROM w_order as o where o.type= 0 and o.uid="+uid+" order by createtime desc";
			List<Order> orderList = Order.dao.find(sql);
			setAttr("orderList", orderList);
			setAttr("none", (orderList==null || orderList.size() == 0) ?null:1);
			render("orderList.html");
		} else if(type ==1){
			sql ="SELECT o.id,o.hid,o.hname,o.STATUS,FROM_UNIXTIME(o.createtime / 1000,'%Y-%m-%d %h:%i' ) as createtime1 , "+AdminController.case_statusname+"  FROM w_order as o where o.type= 0 and o.sid="+uid+" order by createtime desc";
			List<Order> orderList = Order.dao.find(sql);
			
			setAttr("orderList", orderList);
			setAttr("none", (orderList==null || orderList.size() == 0) ?null:1);
			render("orderList.html");
		}
	}
	
	@Before(UserInterceptor.class)
	public void taskList(){
		User user = getSessionAttr("user");
		int uid = user.getInt("id");
		int type = user.getInt("type");
	    if(type ==1){
	    	String sql = "";
	    	sql ="SELECT 0 as distance,h.*,o.parentid, o.id as oid,o.price,FROM_UNIXTIME(o.createtime/1000,'%Y-%m-%d %h:%i' ) as createtime1 ,FROM_UNIXTIME(o.checkintime/1000,'%Y-%m-%d %h:%i' ) as checkintime1 ,FROM_UNIXTIME(o.checkouttime/1000,'%m/%d %h:%i' ) as checkouttime1 ,FROM_UNIXTIME(o.endtime/1000,'%m/%d %h:%i' ) as endtime1 , "+AdminController.case_statusname+"  FROM w_order as o left join w_house as h  on h.id = o.hid where o.status = 0 order by createtime desc";
			List<Order> orderList = Order.dao.find(sql);
			List<Order> newOrderList = new ArrayList<Order>();
			if (user.getDouble("lon").doubleValue() > 0 && user.getDouble("lat").doubleValue() > 0){
				for(Order order:orderList){
					if (order.getDouble("lon").doubleValue() > 0 && order.getDouble("lat").doubleValue() > 0){
						double distance = GeoU.calDistance(order.getDouble("lon"), order.getDouble("lat"), user.getDouble("lon"), user.getDouble("lat"));
						if (distance < 3001){
							order.set("parentid", new BigDecimal(distance/1000).setScale(2,BigDecimal.ROUND_HALF_DOWN));
							newOrderList.add(order);
						}
					}
				}
			}
			setAttr("none", (newOrderList==null || newOrderList.size() == 0) ?null:1);
			setAttr("orderList", newOrderList);
			render("taskList.html");
	    }
	}
	
	@Before(UserInterceptor.class)
	public void meetOrder(){
		Order order = Order.dao.findById(getPara("id"));
		if(order != null){
			if( order.getInt("sid")  == 0 ){
				User user = getSessionAttr("user");
				int uid = user.getInt("id");
				order.set("sid", uid);
				order.set("status", 1); 
				order.update();
				try{
					user.set("ordercnt", user.getInt("ordercnt")+1);
					user.update();
				} catch (Exception e) {
				}
				
			} else {
				renderText("此订单已有安排了!");
				return;
			}
		}
		renderText("操作成功!");
	}
	
	@Before(UserInterceptor.class)
	public void order_detail(){
		Order order = Order.dao.findFirst("SELECT o.* ,FROM_UNIXTIME(o.createtime / 1000,'%Y-%m-%d %h:%i' ) as createtime1 , FROM_UNIXTIME(o.checkintime/ 1000,'%Y-%m-%d %h:%i' ) as checkintime1 ,FROM_UNIXTIME(o.checkouttime/ 1000,'%Y-%m-%d %h:%i' ) as checkouttime1 ,FROM_UNIXTIME(o.endtime/1000,'%Y-%m-%d %h:%i' ) as endtime1 , "+AdminController.case_statusname+"  FROM w_order as o where o.id = "+ getPara("id"));
		if (order != null){
			int status = order.getInt("status");
			User user = getSessionAttr("user");
			if (status == -1){
				setAttr("orderid", getPara("id"));
				setAttr("money", user.get("money"));
				render("choose.html");
			} else {
				User sUser = User.dao.findById(order.get("sid")); 
				// 订单编号
				setAttr("id", order.get("id"));
				setAttr("orderid", order.get("orderid"));
				setAttr("createtime", order.get("createtime1"));
				setAttr("checkintime1", order.get("checkintime1"));
				setAttr("checkouttime1", order.get("checkouttime1"));
				setAttr("endtime1", order.get("endtime1"));
				
				setAttr("status", order.get("status"));
				setAttr("statusname", order.get("statusname"));
				setAttr("five", order.get("five"));
				setAttr("eight", order.get("eight"));
				setAttr("sid", order.get("sid"));
				// 集中点
				setAttr("fid", order.get("fid"));
				setAttr("note", order.get("note"));
				setAttr("price", order.get("price"));
				if(order.get("fid") != null && order.getInt("fid") > 0){
					Focus focus = Focus.dao.findById(order.get("fid"));
					setAttr("fname", focus.get("name"));
					setAttr("faddress", focus.get("address"));
				}
				if (sUser != null){
					setAttr("shead", StringUtil.isEmpty(String.valueOf(sUser.get("head")))? null:sUser.get("head"));
					setAttr("sname", sUser.get("name"));
					setAttr("saccount", sUser.get("account"));
				}
				
				User uUser = User.dao.findById(order.get("uid"));
				if (uUser != null){
					setAttr("sname", uUser.get("name"));
					setAttr("smobile", uUser.get("mobile"));
				}
				
				// [{"price":50,"name":"基础服务"},{"price":50,"name":"厨房深度保洁"},{"price":100,"name":"全屋玻璃清洁"}]
				JSONArray array = JSONArray.fromObject(order.get("pdetail"));
				List<String> options = Lists.newArrayList();
				for(int i = 0 ; i < array.size() ; i++){
					Map<String,Object> map = (Map) array.get(i);
					options.add(String.valueOf(map.get("name")));
				}
				setAttr("options", options);
				/*
				boolean shendu = false;
				boolean qingjie = false;
				for(int i = 0 ; i < array.size() ; i++){
					Map<String,Object> map = (Map) array.get(i);
					if ("厨房深度保洁".equals(map.get("name"))){
						shendu = true;
					} else if ("全屋玻璃清洁".equals(map.get("name"))){
						qingjie = true;
					}
				}
				setAttr("shendu", shendu);
				setAttr("qingjie", qingjie);
				*/
				String bpic = order.getStr("bpic");
				int bpicsize = 0 ;
				if (StringUtil.isEmpty(bpic)){
					
				} else {
					String[] bpicArray = bpic.split(",");
					bpicsize = bpicArray.length;
					setAttr("bpicArray", bpicArray);
				}
				setAttr("bpicsize", bpicsize);
				
				String apic = order.getStr("apic");
				int apicsize = 0 ;
				if (StringUtil.isEmpty(apic)){
					
				} else {
					String[] apicArray = apic.split(",");
					apicsize = apicArray.length;
					setAttr("apicArray", apicArray);
				}
				setAttr("apicsize", apicsize);
				
				int goodssize = 0 ;
				House house = House.dao.findById(order.get("hid"));
				String goods =  house.getStr("goods");
				setAttr("goods", goods);
				if (!StringUtil.isEmpty(goods)){
					String[] goodsArray = goods.split(",");
					goodssize = goodsArray.length;
					setAttr("goodsArray", goodsArray);
				}
				setAttr("goodssize", goodssize);
				setAttr("house", house);
				setAttr("linen", house.get("linen"));
				
				
				setAttr("rentername", order.get("rentername"));
				setAttr("rentermobile", order.get("rentermobile"));
				
				// 登录用户是什么类型
				int sessiontype = ((User) getSessionAttr("user")).getInt("type");
				setAttr("sessiontype", sessiontype);
				render("order_detail.html");
				return;
			}
		} else {
			renderHtml("<h1>订单不存在!</h1>");
			return ;
		}
	}
	
	
	@Before(UserInterceptor.class)
	public void orderSave(){
		User user = (User) getSession().getAttribute("user");
		Order order = Order.dao.findById(getPara("id"));
		String bpic = getPara("bpic");
		String apic = getPara("apic");
		String wxid = user.getStr("wxid");
		// 2 '已入住'  3 '打扫中'  4 '已完成'
		if (order.getInt("status") == 1){
			if (order.getInt("sid").intValue() == user.getInt("id").intValue()){
				order.set("status", 2);
				order.update();
			}
			if (!StringUtil.isEmpty(wxid)){
				WeiXinUtil.orderStatusUpdate(wxid, order.get("id"), "已入住", order.getStr("hname"));
			}
			
		} else if(!StringUtil.isEmpty(bpic) && order.getInt("status") == 2){
			order.set("bpic", bpic);
			order.set("status", 3);
			order.update();
			if (!StringUtil.isEmpty(wxid)){
				WeiXinUtil.orderStatusUpdate(wxid, order.get("id"), "打扫中", order.getStr("hname"));
			}
		} else if(!StringUtil.isEmpty(apic) && order.getInt("status") == 3){
			order.set("apic", apic);
			order.set("status", 4);
			order.update();
			if (!StringUtil.isEmpty(wxid)){
				WeiXinUtil.orderStatusUpdate(wxid, order.get("id"), "已完成", order.getStr("hname"));
			}
			BigDecimal base1 = new BigDecimal("0.6");
			if ("三星".equals(user.getStr("rank"))){
				base1 = new BigDecimal("0.55");
			}
			BigDecimal base = order.getBigDecimal("price").subtract(new BigDecimal(5*(order.getInt("five").intValue()+order.getInt("eight").intValue())));
			BigDecimal xi = new BigDecimal(2*(order.getInt("five").intValue()+order.getInt("eight").intValue()));
			BigDecimal changeMoney = base.multiply(base1).add(xi).setScale(2, BigDecimal.ROUND_DOWN);
			user.set("money", changeMoney.add(user.getBigDecimal("money")));
			user.update();
			if (!StringUtil.isEmpty(wxid)){
				WeiXinUtil.moneyChangeNotice(wxid, changeMoney, user.getBigDecimal("money"));
			}
				/*
			// 东家帮清洗：打扫费*60% + 2元／套
			//房内清洗：打扫费*55% + 3元／套
			// 没有清洗：打扫费*55%
			if (StringUtil.isEmpty(order.getStr("linen"))){
				BigDecimal changeMoney = order.getBigDecimal("price").multiply(new BigDecimal("0.55")).setScale(2, BigDecimal.ROUND_DOWN);
				user.set("money", changeMoney.add(user.getBigDecimal("money")));
				user.update();
				if (!StringUtil.isEmpty(wxid)){
					WeiXinUtil.moneyChangeNotice(wxid, changeMoney, user.getBigDecimal("money"));
				}
			} else if("布草在家清洗".equals(order.getStr("linen"))){
				BigDecimal base = order.getBigDecimal("price").subtract(new BigDecimal(5*(order.getInt("five").intValue()+order.getInt("eight").intValue())));
				// .setScale(2, BigDecimal.ROUND_DOWN)
				BigDecimal xi = new BigDecimal(3*(order.getInt("five").intValue()+order.getInt("eight").intValue()));
				
				BigDecimal changeMoney = base.multiply(new BigDecimal("0.55")).add(xi).setScale(2, BigDecimal.ROUND_DOWN);
				user.set("money", changeMoney.add(user.getBigDecimal("money")));
				user.update();
				if (!StringUtil.isEmpty(wxid)){
					WeiXinUtil.moneyChangeNotice(wxid, changeMoney, user.getBigDecimal("money"));
				}
			} else if("布草清洗".equals(order.getStr("linen"))){
				BigDecimal base = order.getBigDecimal("price").subtract(new BigDecimal(5*(order.getInt("five").intValue()+order.getInt("eight").intValue())));
				BigDecimal xi = new BigDecimal(2*(order.getInt("five").intValue()+order.getInt("eight").intValue()));
				BigDecimal changeMoney = base.multiply(new BigDecimal("0.6")).add(xi).setScale(2, BigDecimal.ROUND_DOWN);
				user.set("money", changeMoney.add(user.getBigDecimal("money")));
				user.update();
				if (!StringUtil.isEmpty(wxid)){
					WeiXinUtil.moneyChangeNotice(wxid, changeMoney, user.getBigDecimal("money"));
				}
			}
			*/
		}
		renderText("操作成功!");
	}
	
	@Before(UserInterceptor.class)
	public void personal(){
		User user = getSessionAttr("user");
		int uid = user.getInt("id");
		int type = user.getInt("type");
		setAttr("uid", user.get("id"));
		setAttr("username", user.get("name"));
		setAttr("money", user.get("money"));
		setAttr("rank", user.get("rank"));
		render("personal"+type+".html");
	}
	
	public void personalSave(){
		User user = User.dao.findById(getPara("id"));
		if (user != null){
			user.set("name", getPara("username"));
			user.update();
			getSession().setAttribute("user", user);
		}
		renderText("操作成功!");
	}
	
	private void renterSMS(String mobile,Long time1,Long time2){
		try {
			if (time1 == null || time1 == 0l){
				QQSMSComponent.sendRenter(mobile,  DateUtil.renterSMS(time2), "18936096300");
			} else {
				QQSMSComponent.sendRenter(mobile, DateUtil.renterSMS(time1), DateUtil.renterSMS(time2), "18936096300");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void newOrderWeixinNotice(double lon ,double lat,Order order,String address){
		List<User> userList = User.dao.find("select * from w_user where type = 1 and wxid != null and lon > 0 and lat > 0");
		for(User user : userList){
			if (GeoU.calDistance(lon, lat, user.getDouble("lon"), user.getDouble("lat")) < 3001){
				String  order_clean = "";
				if (StringUtil.isEmpty(order.getStr("linen"))){
					
				} else if("布草在家清洗".equals(order.getStr("linen"))){
					order_clean = "布草需要在家清洗";
				} else if("布草清洗".equals(order.getStr("linen"))){
					order_clean = "布草需要带出清洗";
				}
				String order_detail =  "服务时间:" + DateUtil.commonShortTimeFormat.format(new Date(order.getLong("checkouttime")))
					+ "～" + DateUtil.commonShortTimeFormat.format(new Date(order.getLong("endtime"))) +" "+order_clean+" "+"地址:太阳路935号";
				WeiXinUtil.newOrderSms(user.getStr("wxid"),order_detail);
			}
		}
	}
	
	
	public void exit(){
		getSession().removeAttribute("user");
		CookiesUtil.remove(getRequest(), getResponse(), "wxid");
		index();
	}
	
	public static void main(String[] args) {
//		System.out.println(GeoU.calDistance(35.104,118.871,35.102,118.877));
		String order_clean = "布草需要在家清洗";
		String order_detail =  "服务时间: 12:00 ～ 14:00 "+order_clean+"\n"+"地址:太阳路935号";
		WeiXinUtil.newOrderSms("ov7Dl0qucgN9iEOeXdeHEmYHpcV4",order_detail);
		System.out.println("ok");
	}
	
	public void test(){
		String order_clean = "布草需要在家清洗";
		String order_detail =  "服务时间: 12:00 ～ 14:00 "+order_clean+"\n"+"地址:太阳路935号";
		WeiXinUtil.newOrderSms(getPara("wxid"),order_detail);
		renderText("发送成功!");
	}
	
}
